package com.easyfun.healthmagicbox.comm;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.content.Context;
import android.util.Log;

import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.json.HealthInputListJsonWrapper;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.HealthInputData;
import com.easyfun.healthmagicbox.sync.CommCallback;
import com.j256.ormlite.dao.Dao;

public class HealthInputDataUploadTask extends BaseRedoTask implements
		Runnable, DatabaseAccess {

	String mpersonalID;

	public HealthInputDataUploadTask(Context context,CommCallback callback)
	{
		super(context,callback);
	}
	
	public HealthInputDataUploadTask(Context context, String persionID,
			CommCallback callback) {

		super(context,callback);
		mpersonalID = persionID;
	}

	@Override
	public void run() {
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("personID", mpersonalID);
			map.put("syncid", 0);		//find out unsync data
			Dao<HealthInputData, Integer> inputdao = getHelper(mcontext)
					.getInputDataDao();
			List<HealthInputData> pps = inputdao.queryForFieldValues(map);
			String tmp;
			if (pps.size() > 0) {

				//BUG #4
				HealthInputDataDownloadTask downloadFirst = 
						new HealthInputDataDownloadTask(mcontext, mpersonalID, ccb);
/*				HealthThreadPool.getInstance().execute(downloadFirst);
*/				
				downloadFirst.run();
				//-------------------------------
				HealthInputListJsonWrapper<?> wrapper = new HealthInputListJsonWrapper(
						pps);
				tmp = wrapper.serialize();

				Map<String, String> parmas = new HashMap<String, String>();
				parmas.put("jsonstring", tmp);
				String result = super.uploadByHTTP(parmas,
						ConstantData.InputDatatPOSTURI);
				Log.d("syncManager", "Json string = " + parmas);
				if (ServerResponseCode.parseOf(result)==ServerResponseCode.FAILED)
				{

					ccb.setCommResult(this,
							"", ServerResponseCode.FAILED);
					return;
				}
				if (result.length()>0) {
					String[] ss=result.split("\\,");
			        int i=0;
			        
					int size = ss.length;// 3 & 5
					if (size != pps.size()) {
						// the count is not match result is failed.
						ccb.setCommResult(this,
								"",ServerResponseCode.FAILED);
					} else {
						while(i<ss.length)
				        {
							String[] idPairs = ss[i].split("\\:");
							for(int m = 0; m < pps.size(); m ++) {
								if(pps.get(m).getId() == Integer.valueOf(idPairs[0])) {
									pps.get(m).setId(Integer.valueOf(idPairs[0]));
									if(idPairs[1] == null) {
										pps.get(m).setSyncid(0);
									}else {
										pps.get(m).setSyncid(Integer.valueOf(idPairs[1]));
									}
									
									//search
									List<HealthInputData> data = inputdao.queryForEq("syncid", idPairs[1]);
									if(data.size() > 0) {
										inputdao.delete(pps.get(m));
									} else{
										inputdao.createOrUpdate(pps.get(m));
									}
								}
							}
						/*	HealthInputData tmpinput = pps.get(i);
							
							tmpinput.setSyncid(Integer.valueOf(ss[i]));
							inputdao.createOrUpdate(tmpinput);*/
							i++;
						}
						ccb.setCommResult(this,
								mpersonalID, ServerResponseCode.SUCCESS);
					}
					return;
				}else
				{
					ccb.setCommResult(this,
							"",ServerResponseCode.FAILED);
					return;
				}
				
			}else
			{
				ccb.setCommResult(this,
						"",ServerResponseCode.NOMORE);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ccb.setCommResult(this, mpersonalID,
					ServerResponseCode.FAILED);
		}

	}

	@Override
	public DatabaseHelper getHelper(Context context) {

		return DatabaseAccessImplementation.getInstance().getHelper(mcontext);
	}

	@Override
	public String serializeParam() throws IllegalArgumentException{
		return mpersonalID;
	}

	@Override
	public void deserializeParam(String serialstring) throws IllegalArgumentException{
		mpersonalID = serialstring;
		
	}

}
